package com.zx.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.usercenter.common.ErrorCode;
import com.zx.usercenter.exception.BusinessException;
import com.zx.usercenter.model.domain.User;
import com.zx.usercenter.service.UserService;
import com.zx.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zx.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author Bro
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-04-17 12:20:16
 */
@Service
@Slf4j
public class  UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "zhangxu";


    /**
     * @param userAccount   用户账号
     * @param userPassword  用户密码
     * @param checkPassword 二次密码
     * @return //
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //检测参数不能为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }
        //检测账号长度不小于6
        if (userAccount.length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于6位");
        }
        //检测密码长度不小于8
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度小于8位");
        }

        //账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘； ：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }

        //检测两次密码必须相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }

        //账号不能重复
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserAccount, userAccount);
        long count = userMapper.selectCount(wrapper);
        if (count > 0) {
            return -1;
        }

        //密码md5加密
        String encryptPaw = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //插入数据

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPaw);
        int insert = userMapper.insert(user);
        if (insert != 1) {
            return -1;
        }

        return user.getId();

    }

    @Override
    public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //检测不为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
           throw new BusinessException(ErrorCode.NULL_ERROR,"请求参数为空");
        }
        //检测长度
        if (userAccount.length() < 6 || userPassword.length() < 8) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码长度过短");
        }
        //检测非法字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘； ：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }
        //对密码进行加密
        String encryptPaw = DigestUtils.md5DigestAsHex(userPassword.getBytes());
        //查询数据库
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUserAccount, userAccount);
        lqw.eq(User::getUserPassword, encryptPaw);
        User user = userMapper.selectOne(lqw);
        if (user == null) {
            log.info("user login failed,userAccount or userPassword can not match");
           throw new BusinessException(ErrorCode.NULL_ERROR,"该用户不存在");
        }

        //脱敏
        User safetyUser = getSafetyUser(user);


        //用户登录成功，保存脱敏后的登录信息
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        //将脱敏后的用户信息返回
        return safetyUser;
    }

    @Override
    public User getSafetyUser(User user) {
        if (user == null) {
            return null;
        }
        User safetyUser = new User();

        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setCreateTime(user.getCreateTime());
        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




